<template>
  <view class="bg"></view>
  <view class="wrapper">
    <image class="build-img" src="@/pageAuth/static/2.png"></image>
    <image class="yunbao-img" src="@/pageAuth/static/4.png"></image>
    <view class="bg-2"></view>
    <view class="bg-1"></view>
    <view
      class="bg-ffffff absolute top-0 left-0 wp-100 hp-100 border-radius-24 column align-center"
    >
      <image style="width:150rpx;height: 150rpx;margin-top: 20rpx" src="@/pageAuth/static/logo.jpg"></image>
      <view class="fs-40 cl-1e262f mt-48">欢迎注册/登录四川选星计划</view>
      <button @tap="toLogin" class="wx-btn" :loading="logining">
        四川选星计划一键登录
      </button>
    </view>
    <image class="yunbao-shou-img" src="@/pageAuth/static/5.png"></image>
    <view
      class="m-protocal absolute bottom-64 left-0 wp-100 hp-40 row align-center relative justify-center"
      @tap="agreeProtocol"
    >
      <view
        class="btn mr-16 w-32 h-32 border-radius-32 row align-center justify-center"
        :class="{
          active: bindRange,
        }"
      >
        <image class="w-20 h-20" src="@/pageAuth/static/7.png"></image>
      </view>
      <text class="txt-6 fs-24">阅读并同意</text>
      <feedback @feed-tap.stop="toProtocol('隐私政策')">
        <text class="cl-408af7 fs-24">《隐私政策》</text>
      </feedback>
      <feedback @feed-tap.stop="toProtocol('服务协议')">
        <text class="cl-408af7 fs-24">《服务协议》</text>
      </feedback>
    </view>
  </view>
</template>
<script lang="ts" setup>
  import { computed, ref } from 'vue'
  import feedback from '@/components/feedback/index.vue'
  import { toProtocol } from './hooks'
  import { hideLoading, msg } from '../../utils/tools'
  import { uniapp } from '../../utils/uni'
  import { threePartiesLogin } from '../../api/login'
  import { useStore } from 'vuex'
  import { SET_TGT_TOKEN, SET_USER_INFO } from '@/store/types'
  import { uploadUserInfo } from '@/api/auth'
  import { onUnload } from '@dcloudio/uni-app'
  import { useClearLoginChannelRelations } from '@/hooks/hooks'
  import uma from '@/utils/uma'
  import { usePlatform } from '../../hooks/usePlatform'
  import { Platform } from '../../interface'
  import { conbineUrlParams } from '@/utils/common'
  import { getUserInfoFromAccountSys } from '@/hooks/useSaveUserInfo'

  const logining = ref(false)
  const bindRange = ref(false)
  const store = useStore()
  const commit = store.commit
  const isToBindPhone = ref(false)

  const userInfo = computed(() => store.state.user.userInfo)

  // 点击登录
  const toLogin = async () => {
    if (logining.value) return msg('登陆中')
    if (!bindRange.value) return msg('请先同意协议')
    uma.trackEvent('setting', { title: '用户一键登录' })
    logining.value = true
    try {
      let userInfo: { userInfo?: any } = {}
      // #ifdef MP-WEIXIN
      // uniapp 获取微信登录用户信息
      userInfo = await uniapp('getUserProfile', {
        desc: '显示用户头像',
      })

      if (userInfo.userInfo) {
        uni.setStorageSync('userInfo', userInfo.userInfo)
        commit(`user/${SET_USER_INFO}`, userInfo.userInfo)
      }

      // #endif

      // uniapp 微信授权
      const { code: authCode } = await uniapp('login', {
        provider: usePlatform() === Platform.alipay ? '' : 'weixin',
        scopes: 'auth_user',
        onlyAuthorize: true,
      })

      uma.trackEvent('auth', { title: '用户同意授权' })
      // 账号系统授权
      login({
        ...userInfo,
        authCode,
      })
    } catch (error) {
      logining.value = false
      console.log(error)
      uma.trackEvent('auth', { title: '用户取消授权' })
      msg('授权失败')
    }
  }

  const tgt = computed(() => store.state.user.TGT)

  onUnload(() => {
    if (!tgt.value && !isToBindPhone.value) {
      useClearLoginChannelRelations()
    }
  })

  // 账号系统授权
  const login = async (data: any) => {
    try {
      const signData = JSON.parse(JSON.stringify(data))
      delete signData.userInfo
      delete signData.errMsg
      delete signData.cloudID

      const {
        code,
        data: threeRes,
        msg,
      } = await threePartiesLogin({
        ...signData,
        type: usePlatform() === Platform.alipay ? 1 : 0,
        isSmallProgram: 1,
      })
      if (+code === 20038) {
        // msg('未绑定手机号')
        logining.value = false
        isToBindPhone.value = true
        return uni.redirectTo({
          url: `/pageAuth/bindPhone/bindPhone?authCode=${data.authCode}`,
        })
      }

      if (+code === 200) {
        // alipay微信用户首次登录支付宝注册账号
        if (!threeRes.tgt && threeRes.openId) {
          logining.value = false
          isToBindPhone.value = true
          return uni.redirectTo({
            url: `/pageAuth/verifyMobile/verifyMobile?${conbineUrlParams(
              threeRes
            )}`,
          })
        }
        uni.setStorageSync('threePartLoginData', threeRes)
        store.commit(`user/${SET_TGT_TOKEN}`, threeRes.tgt)
        await getUserInfoFromAccountSys(threeRes.tgt)
        logining.value = false
        uni.$emit('loginSuccess', true)
      }
    } catch (e) {
      logining.value = false
      msg('登录失败，请稍后重试')
    }
  }

  // 同意协议
  const agreeProtocol = function () {
    bindRange.value = !bindRange.value
  }

  const upload = async (data: {
    aid: string
    tgt: string
    userDTO: AnyObject
    openId:string
    // code?: string
  }) => {
    try {
      await uploadUserInfo(data)
    } catch (e) {
      msg('上传登录信息失败，请卸载小程序后重新登录')
      //TODO handle the exception
    }
    return Promise.resolve()
  }
</script>
<style lang="scss" scoped>
  .bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-image: linear-gradient(180deg, #EFF7E8 0%, #FFFFFF 100%);
  }

  .border-radius-24 {
    border-radius: 24rpx;
  }

  .wrapper {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 670rpx;
    height: calc(1104 * 100 / 1624 * 1vh);
    background: #ffffff;
    border-radius: 24rpx;
    .build-img {
      position: absolute;
      top: -200rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 590rpx;
      height: 338rpx;
      animation: scale ease-in 1.5s 1;
    }
    .yunbao-img {
      position: absolute;
      top: -200rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 240rpx;
      height: 240rpx;
    }

    .yunbao-shou-img {
      position: absolute;
      top: -13rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 160rpx;
      height: 40rpx;
    }
    .wx-btn {
      margin-top: 240rpx;
      width: 574rpx;
      height: 88rpx;
      background-image: linear-gradient(-45deg, #75befc 0%, #408af7 100%);
      box-shadow: 0 8rpx 16rpx 0 rgba(64, 138, 247, 0.3);
      border-radius: 44rpx;
      font-weight: 500;
      font-size: 30rpx;
      color: #ffffff;
      text-align: center;
    }

    .m-protocal {
      .btn {
        background: #e0dfdf;
        transition: all 0.3s linear;
        &.active {
          background: #408af7;
        }
      }
    }
  }

  @each $var in 360 40 32 {
    .w-#{$var} {
      width: $var * 1rpx;
    }

    .border-radius-#{$var} {
      border-radius: $var * 1rpx;
    }
  }

  .txt-6 {
    color: rgba(30, 38, 47, 0.6);
  }

  .bg-1 {
    position: absolute;
    top: 230rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 606rpx;
    height: calc(906 * 100 / 1624 * 1vh);
    opacity: 0.6;
    background: #ffffff;
    border-radius: 24rpx;
    animation: move1 linear 1.5s 1;
  }

  .bg-2 {
    position: absolute;
    top: 262rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 542rpx;
    height: calc(906 * 100 / 1624 * 1vh);
    opacity: 0.2;
    background: #ffffff;
    border-radius: 24rpx;
    animation: move2 linear 2s 1;
  }

  @keyframes move1 {
    0% {
      top: 0;
    }

    85% {
      top: 262rpx;
    }
    100% {
      top: 230rpx;
    }
  }

  @keyframes move2 {
    0% {
      top: 0;
    }
    85% {
      top: 292rpx;
    }
    100% {
      top: 262rpx;
    }
  }

  @keyframes scale {
    0% {
      transform: translateX(-50%) scale(0.5);
    }
    100% {
      transform: translateX(-50%) scale(1);
    }
  }
</style>
